package com.luofan.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.luofan.common.result.ResultCodeEnum;
import com.luofan.entity.po.Section;
import com.luofan.entity.po.User;
import com.luofan.entity.vo.SectionMemberVO;
import com.luofan.entity.vo.SectionVO;
import com.luofan.mapper.SectionMapper;
import com.luofan.service.SectionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 教研室表 服务实现类
 * </p>
 *
 * @author
 * @since 2025-03-26
 */
@Service
public class SectionServiceImpl extends ServiceImpl<SectionMapper, Section> implements SectionService {

    @Autowired
    private SectionMapper sectionMapper;

    //获取所有教研室信息列表
    @Override
    public List<SectionVO> listAllSection() {
        List<SectionVO> sectionVOList = sectionMapper.listAllSection();
        return sectionVOList;
    }

    //根据用户id获取用户所在的教研室的信息
    @Override
    public Section getSectionByUserId(Long userId) {
        return sectionMapper.getSectionByUserId(userId);
    }


    //根据教研室id获取所属的成员信息
    @Override
    public SectionMemberVO listMember(Long sectionId) {
        //获取教研室所有成员信息(id,name,email,role)
        List<User> memberList = sectionMapper.listMember(sectionId);

        //将memberList中role为2的用户单独取出来，作为主任信息，如果没有主任则将VO的head设为null
        SectionMemberVO sectionMemberVO = new SectionMemberVO();
        if (ObjectUtil.isEmpty(memberList)) return sectionMemberVO;
        User head = null;

        //使用迭代器遍历元素 避免直接在for循环中使用remove()导致在修改集合的结构时仍在迭代它而产生的报错
        Iterator<User> iterator = memberList.iterator();
        while (iterator.hasNext()) {
            User member = iterator.next();
            if (member.getRole() == 2) {
                head = member;
                sectionMemberVO.setHead(head);
                iterator.remove();  // 使用 Iterator 的 remove() 方法
            }
        }
        sectionMemberVO.setMember(memberList);

        return sectionMemberVO;
    }

    //管理员 新增教研室
    @Override
    public ResultCodeEnum saveSection(String name) {
        //查看是否存在重复的教研室名称
        int count = sectionMapper.countSectionByName(name);
        if (count > 0) return ResultCodeEnum.EXIST_ERROR;

        //添加教研室信息
        int rows = sectionMapper.insert(new Section().setName(name));
        if (rows == 0) return ResultCodeEnum.FAIL;

        return ResultCodeEnum.SUCCESS;
    }

    //管理员 修改教研室名称
    @Override
    public ResultCodeEnum updateSection(Section section) {
        //查看是否存在重复的教研室名称
        int count = sectionMapper.countSectionByName(section.getName());
        if (count > 0) return ResultCodeEnum.EXIST_ERROR;

        //修改教研室名称
        int rows = sectionMapper.updateSectionName(section);
        if (rows == 0) return ResultCodeEnum.FAIL;

        return ResultCodeEnum.SUCCESS;
    }

}
